package com.sgb.packers.view.activity;

import android.text.TextUtils;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.core.util.Pair;
import androidx.lifecycle.Observer;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.listener.OnRefreshLoadMoreListener;
import com.sgb.link.router.PathTeam;
import com.sgb.net.entity.ListResponse;
import com.sgb.packers.R;
import com.sgb.packers.databinding.PackersActivityRecordWorkAccountBookBinding;
import com.sgb.packers.entity.PressDayCalendarEntity;
import com.sgb.packers.entity.WorkStatisticsEntity;
import com.sgb.packers.entity.WorkTakeEntity;
import com.sgb.packers.utils.SchemeUtils;
import com.sgb.packers.view.adapter.WorkAccountChildAdapter;
import com.sgb.packers.viewmodel.RecordWorkAccountBookViewModel;
import com.sgb.younghow.calendarview.Calendar;
import com.sgb.younghow.calendarview.CalendarView;
import com.swgk.core.common.base.TeamBaseActivity;
import com.swgk.core.common.utils.ActivityJump;
import com.swgk.core.util.DateUtils;
import com.swgk.core.xrecyclerview.XRecyclerView;

import org.jetbrains.annotations.NotNull;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;

/**
 * @author : younghow
 * @date  : 2020/11/2
 * Description:个人记工账本页面
 */
@Route(path = PathTeam.RecordWorkAccountBookActivity)
public class RecordWorkAccountBookActivity extends TeamBaseActivity<RecordWorkAccountBookViewModel, PackersActivityRecordWorkAccountBookBinding> implements CalendarView.OnMonthChangeListener, CalendarView.OnCalendarInterceptListener, CalendarView.OnCalendarSelectListener, OnRefreshLoadMoreListener, BaseQuickAdapter.OnItemClickListener {

    @Autowired(name = "projectName", desc = "项目名称")
    String projectName;

    @Autowired(name = "year", desc = "年")
    int year;

    @Autowired(name = "month", desc = "月")
    int month;

    @Autowired(name = "day", desc = "日")
    int day;

    @Autowired(name = "projectNo", desc = "日")
    String projectNo;

    private boolean isInit = true;
    private int page;
    private WorkAccountChildAdapter mAdapter;
    private final List<WorkTakeEntity.ListDTO> mList = new ArrayList<>();

    @Override
    protected Class<RecordWorkAccountBookViewModel> createVM() {
        return RecordWorkAccountBookViewModel.class;
    }

    @Override
    protected void initView() {
        ARouter.getInstance().inject(this);
        mBinding.calendarView.setOnViewChangeListener(isMonthView -> {
            if (isMonthView){
                mBinding.ivExpand.setImageResource(R.mipmap.retract);
                mBinding.tvExpand.setText("收起");
            }else {
                mBinding.ivExpand.setImageResource(R.mipmap.expand);
                mBinding.tvExpand.setText("展开");
            }
        });

        initLiveData();

        initListener();
        
        mBinding.tvFragmentTradePublishSelectType.setText(projectName);
        mBinding.tvFragmentTradePublishTags.setText(String.format("%s年%s月",year,month));

        String[] split = DateUtils.timestamp2DateNumber(System.currentTimeMillis());

        mBinding.calendarView.scrollToCalendar(year,month,day);
        mBinding.calendarView.setRange(2000, 1, 1, Integer.parseInt(split[0]), Integer.parseInt(split[1]), Integer.parseInt(split[2]));
        Calendar calendar = new Calendar();
        calendar.setYear(year);
        calendar.setMonth(month);
        calendar.setDay(day);
        mBinding.calendarView.putMultiSelect(calendar);

        mBinding.rvNoteTake.setLayoutManager(new LinearLayoutManager(this));
        mAdapter = new WorkAccountChildAdapter(mList);
        mAdapter.setOnItemClickListener(this);
        mBinding.rvNoteTake.setAdapter(mAdapter);

        mBinding.refreshLayout.setEnableRefresh(false);
        mBinding.refreshLayout.setEnableLoadMore(true);

        mBinding.calendarView.setWeeColor(0,0xff666666);
        mAdapter.bindToRecyclerView(mBinding.rvNoteTake);
        mAdapter.setEmptyView(R.layout.library_no_data);
        mList.clear();
        mAdapter.notifyDataSetChanged();
    }

    private void initListener() {
        mBinding.rlExpand.setOnClickListener(this);
        mBinding.calendarView.setOnMonthChangeListener(this);
        mBinding.calendarView.setOnCalendarInterceptListener(this);
        mBinding.calendarView.setOnCalendarSelectListener(this);
        mBinding.refreshLayout.setOnRefreshLoadMoreListener(this);
        mBinding.tvTakeWork.setOnClickListener(this);
        mBinding.actionBar.setOnBackClickListener(v -> finish());
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        if (v.getId() == R.id.rl_expand) {
            if (mBinding.calendarLayout.isExpand()) {
                mBinding.calendarLayout.shrink();
            } else {
                mBinding.calendarLayout.expand();
            }
        }else if (v.getId() == R.id.tv_take_work){
            ActivityJump.startActivity(PathTeam.PersonGetWorkActivity, Pair.create("projectName", projectName), Pair.create("projectNo", projectNo), Pair.create("year", year), Pair.create("month", month), Pair.create("day", day));
        }
    }

    private void initLiveData() {
        mViewModel.mPressDayLiveData.observe(this, new Observer<List<PressDayCalendarEntity>>() {
            @Override
            public void onChanged(List<PressDayCalendarEntity> pressDayCalendarEntities) {
                Map<String, Calendar> map = new HashMap<>();
                for (PressDayCalendarEntity pressDayCalendarEntity : pressDayCalendarEntities) {
                    String[] split = pressDayCalendarEntity.getWorkDate().split("-");
                    if (TextUtils.isEmpty(pressDayCalendarEntity.getCalendarInfo())) {
                        continue;
                    }

                    if (pressDayCalendarEntity.getCalendarInfo().contains("个工")) {
                        map.put(SchemeUtils.getSchemeCalendar(Integer.parseInt(split[0]), Integer.parseInt(split[1]), Integer.parseInt(split[2]), 0xFFef4033, pressDayCalendarEntity.getCalendarInfo()).toString(),
                                SchemeUtils.getSchemeCalendar(Integer.parseInt(split[0]), Integer.parseInt(split[1]), Integer.parseInt(split[2]), 0xFFef4033, pressDayCalendarEntity.getCalendarInfo()));
                    } else if (pressDayCalendarEntity.getCalendarInfo().contains("包工")) {
                        map.put(SchemeUtils.getSchemeCalendar(Integer.parseInt(split[0]), Integer.parseInt(split[1]), Integer.parseInt(split[2]), 0xFFED9E13, pressDayCalendarEntity.getCalendarInfo()).toString(),
                                SchemeUtils.getSchemeCalendar(Integer.parseInt(split[0]), Integer.parseInt(split[1]), Integer.parseInt(split[2]), 0xFFED9E13, pressDayCalendarEntity.getCalendarInfo()));
                    } else if (pressDayCalendarEntity.getCalendarInfo().contains("加班")) {
                        map.put(SchemeUtils.getSchemeCalendar(Integer.parseInt(split[0]), Integer.parseInt(split[1]), Integer.parseInt(split[2]), 0xFFEF4033, pressDayCalendarEntity.getCalendarInfo()).toString(),
                                SchemeUtils.getSchemeCalendar(Integer.parseInt(split[0]), Integer.parseInt(split[1]), Integer.parseInt(split[2]), 0xFFEF4033, pressDayCalendarEntity.getCalendarInfo()));
                    } else if (pressDayCalendarEntity.getCalendarInfo().contains("小时")){
                        map.put(SchemeUtils.getSchemeCalendar(Integer.parseInt(split[0]), Integer.parseInt(split[1]), Integer.parseInt(split[2]), 0xFFEF4033, pressDayCalendarEntity.getCalendarInfo()).toString(),
                                SchemeUtils.getSchemeCalendar(Integer.parseInt(split[0]), Integer.parseInt(split[1]), Integer.parseInt(split[2]), 0xFFEF4033, pressDayCalendarEntity.getCalendarInfo()));
                    }
                }
                mBinding.calendarView.setSchemeDate(map);

                if (isInit){
                    mBinding.calendarLayout.shrink();
                    isInit = false;
                }
                mBinding.tvExpand.setText("展开");
            }
        });

        mViewModel.mStatisticsLiveData.observe(this, listListResponse -> {
            mBinding.refreshLayout.finishLoadMore();
            if (page == 1) {
                mList.clear();
            }
            if (listListResponse.getList() == null || listListResponse.getList().size() <= 0){
                mList.clear();
                mAdapter.notifyDataSetChanged();
                return;
            }
            if (listListResponse.getList().get(0).getList() != null) {
                mList.addAll(listListResponse.getList().get(0).getList());
            }
            mAdapter.notifyDataSetChanged();
            if (listListResponse.getCurrentPage() < listListResponse.getTotalPage()) {
                mBinding.refreshLayout.resetNoMoreData();
            } else {
                mBinding.refreshLayout.finishLoadMoreWithNoMoreData();
            }
        });
    }

    @Override
    protected void initData() {
        pressDay(year,month);
        getWorkStatistics(false);
    }

    private void pressDay(int year,int month) {
        String month1 = month >= 10 ? String.valueOf(month) : String.format(Locale.CHINA, "0%d", month);
        Map<String, Object> map = new HashMap<>();
        map.put("month", month1);
        map.put("projectNo", projectNo);
        map.put("type", 1);
        map.put("year", year);
        mViewModel.pressDay(map);
    }

    private void getWorkStatistics(boolean isLoadMore){
        String month1 = month >= 10 ? String.valueOf(month) : String.format(Locale.CHINA, "0%d", month);
        String day1 = day >= 10 ? String.valueOf(day) : String.format(Locale.CHINA, "0%d", day);
        page = isLoadMore ? page++ : 1;
        Map<String, Object> map = new HashMap<>();
        map.put("limit", 20);
        map.put("month", month1);
        map.put("projectNo", projectNo);
        map.put("page", 1);
        map.put("day", day1);
        map.put("year", year);
        map.put("type", 1);
        mViewModel.takeWorkAccount(map);
    }

    @Override
    protected int layoutId() {
        return R.layout.packers_activity_record_work_account_book;
    }


    @Override
    public void onMonthChange(int year, int month) {
        pressDay(year,month);
        mBinding.tvFragmentTradePublishTags.setText(String.format(Locale.CHINA, "%d年%d月", year, month));
    }

    @Override
    public boolean onCalendarIntercept(Calendar calendar) {
        return calendar.getYear() > mBinding.calendarView.getCurYear() ||
                (calendar.getYear() == mBinding.calendarView.getCurYear() && calendar.getMonth() > mBinding.calendarView.getCurMonth()) ||
                (calendar.getYear() == mBinding.calendarView.getCurYear() && calendar.getMonth() == mBinding.calendarView.getCurMonth() &&
                        calendar.getDay() > mBinding.calendarView.getCurDay());
    }

    @Override
    public void onCalendarInterceptClick(Calendar calendar, boolean isClick) {

    }

    @Override
    public void onCalendarOutOfRange(Calendar calendar) {

    }

    @Override
    public void onCalendarSelect(Calendar calendar, boolean isClick) {
        year = calendar.getYear();
        month = calendar.getMonth();
        day = calendar.getDay();
        getWorkStatistics(false);
    }

    @Override
    public void onLoadMore(@NonNull @NotNull RefreshLayout refreshLayout) {
        getWorkStatistics(true);
    }

    @Override
    public void onRefresh(@NonNull @NotNull RefreshLayout refreshLayout) {

    }

    @Override
    public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
        if ("1".equals(mList.get(position).getrType())){
            ActivityJump.startActivity(PathTeam.PointWorkEditActivity, Pair.create("projectName", projectName), Pair.create("projectNo", projectNo), Pair.create("year", year), Pair.create("month", month), Pair.create("day", day), Pair.create("no", mList.get(position).getWorkRecordNo()));
        }else if ("2".equals(mList.get(position).getrType())){
            ActivityJump.startActivity(PathTeam.JobWorkEditActivity, Pair.create("projectName", projectName), Pair.create("projectNo", projectNo), Pair.create("year", year), Pair.create("month", month), Pair.create("day", day), Pair.create("no", mList.get(position).getWorkRecordNo()));
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        pressDay(year,month);
        getWorkStatistics(false);
    }
}
